/**
 * @Author 天下无敌
 * @Date 
 * @AIDE AIDE+ 
 */
package com.ecs.core.gsystem.chunk;
import com.artemis.BaseEntitySystem;
import com.artemis.annotations.All;
import com.ecs.core.GameContext;
import com.ecs.core.gsystem.player.PlayerDataSystem;
import com.artemis.ComponentMapper;
import com.ecs.core.EntityBuilder;
import com.ecs.core.components.map.ChunkCom;
import com.ecs.core.components.map.ChunkPosCom;


@All({ChunkCom.class,ChunkPosCom.class})//获取全部区块，判断是否卸载
public class ChunkSystem extends BaseEntitySystem
{
	public static final String TAG = "ChunkSystem";
	
	private PlayerDataSystem playerSystem;
    private final int loadRadius = 2; 
    private final int chunkSize = GameContext.CHUNK_SIZE; // 区块大小

    private ChunkPosCom oldPos = new ChunkPosCom();
    private ChunkPosCom currentPos = new ChunkPosCom();

	private ComponentMapper<ChunkCom> chunkComs;
	private ComponentMapper<ChunkPosCom> chunkPosComs;
	@Override
	protected void initialize()
	{
		super.initialize();
		oldPos.chunkX = Integer.MIN_VALUE;
		oldPos.chunkY= Integer.MIN_VALUE;
	}


    @Override
    protected void processSystem() {
        // 玩家位置
		currentPos.chunkX = worldToChunk(playerSystem.getPlayerCenterX());
		currentPos.chunkY =  worldToChunk(playerSystem.getPlayerCenterY());
		
		if(currentPos.chunkX == oldPos.chunkX && currentPos.chunkY == oldPos.chunkY){return;}

        oldPos.chunkX = currentPos.chunkX;
		oldPos.chunkY = currentPos.chunkY;

        // 处理区块加载和卸载
        updateChunks();
    }

    private void updateChunks() {
        // 1. 标记需要卸载的区块
        markChunksForUnloading();

        // 3. 加载新区块
        loadNewChunks();
    }

    private void markChunksForUnloading() {
        // 遍历所有区块实体
        for (int i = 0;i < getEntityIds().size();i++) {
			int chunkEntity = getEntityIds().get(i);
            ChunkCom chunk = chunkComs.get(chunkEntity);
            ChunkPosCom pos = chunkPosComs.get(chunkEntity);

            // 如果区块超出加载范围，则标记为卸载
			int deX = Math.abs(currentPos.chunkX - pos.chunkX);
			int deY = Math.abs(currentPos.chunkY - pos.chunkY);
            if (deX > loadRadius || deY > loadRadius) {
                chunk.isUnload = true;
				//Debug.log(TAG,String.format("unloadChunk coord: %d,%d",pos.chunkX,pos.chunkY));
            }else{
				//没有超出范围，并且被设置为卸载，取消卸载
				if(chunk.isUnload){
					chunk.isUnload = false;
				}
			}
        }
    }

    private void loadNewChunks() {
        // 计算需要加载的区块范围
        int minX = currentPos.chunkX - loadRadius;
        int maxX = currentPos.chunkX + loadRadius;
        int minY = currentPos.chunkY - loadRadius;
        int maxY = currentPos.chunkY + loadRadius;

        // 遍历范围内的所有区块
        for (int x = minX; x <= maxX; x++) {
            for (int y = minY; y <= maxY; y++) {
                // 检查区块是否已存在
                if (!isChunkLoaded(x, y)) {
                    // 创建新区块
                    createChunk(x, y);
					//Debug.log(TAG,String.format("createChunk coord: %d,%d",x,y));
                }
            }
        }
    }

    private boolean isChunkLoaded(int chunkX, int chunkY) {
        for (int i = 0;i < getEntityIds().size();i++) {
			int chunkEntity = getEntityIds().get(i);
            ChunkPosCom pos = chunkPosComs.get(chunkEntity);
            if (pos.chunkX == chunkX && pos.chunkY == chunkY) {
                return true;
            }
        }
        return false;
    }

    private void createChunk(int chunkX, int chunkY) {
        EntityBuilder.init(world)
			.Chunk()
			.Pos(chunkToWorld(chunkX),chunkToWorld(chunkY))
			.ChunkPos(chunkX,chunkY)
			.Scale(chunkSize,chunkSize);
    }

	public int worldToChunk(float worldCoord){
		return (int)Math.floor(worldCoord / chunkSize);
	}
	public float chunkToWorld(int chunkCoord){
		return (float)chunkCoord * chunkSize;
	}

	//调试
	public int ChunkCount(){
		return getEntityIds().size();
	}

	
}
